package com.web.activiti.controller;

import com.web.activiti.mapper.SysPermissionCustomMapper;
import com.web.activiti.pojo.*;
import com.web.activiti.service.EmployeeService;
import com.web.activiti.service.ReimbFlowService;
import com.web.activiti.service.SysService;
import com.web.activiti.utils.Contants;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.junit.internal.runners.JUnit4ClassRunner;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.*;

@Controller   //Reimbursement flow 报销流
public class ReimbFlowController {
    @Autowired
    private ReimbFlowService ReimbFlowService;      //报销流服务层
    @Autowired
    private SysPermissionCustomMapper sysPermissionCustomMapper;  //权限扩展的映射
    @Autowired
    private SysService sysService;  //shiro安全框架的映射
    @Autowired
    private EmployeeService employeeService;  //用户类的服务层


    /**
     * 保存报销单
     * @param baoXiaoBill
     * @param session
     * @return
     */
    @RequestMapping("/saveStartBaoxiao")
    public String saveStartLeave(BaoXiaoBill baoXiaoBill, HttpSession session){
        System.out.println("saveStartBaoxiao....");
        ActiveUser user = (ActiveUser) session.getAttribute(Contants.GLOBAL_SESSION_ID);
        Employee employee=new Employee();
        employee.setId(user.getId());
        employee.setName(user.getUsername());
        ReimbFlowService.saveStartProcess(baoXiaoBill,employee );
        return "redirect:/myBXTaskList";
    }

    /**
     * 查看我的代办
     * @param session
     * @return
     */
    @RequestMapping("/myBXTaskList")
    public ModelAndView myTaskList(HttpSession session){
        System.out.println("myBXTaskList...  ");
        ActiveUser employee = (ActiveUser) session.getAttribute(Contants.GLOBAL_SESSION_ID);
        List<Task> taskList = ReimbFlowService.findTaskListByUserId(employee.getUsername());
        ModelAndView mv = new ModelAndView();
        mv.addObject("taskList", taskList);
        mv.setViewName("workflow_task");
        return mv;
    }

    /**
     * 进入办理页面  并打印出批注
     * @param taskId
     * @return
     */
    @RequestMapping("/BXviewTaskForm")
    public ModelAndView viewTaskForm(String taskId){
        System.out.println("BXviewTaskForm。。。。");
        //根据流程数据的 数据查s询请假业务表的数据 business_key
        BaoXiaoBill baoxiaobill=ReimbFlowService.findBillByTask(taskId);
        //查询批注
        List<Comment> commentList = ReimbFlowService.findCommentList(taskId);
        List<String> come = ReimbFlowService.findOutComeListByTaskId(taskId);
        ModelAndView mv = new ModelAndView();
        mv.addObject("outcomeList",come);
        mv.addObject("bill", baoxiaobill);
        mv.addObject("commentList", commentList);
        mv.addObject("taskId", taskId);
        mv.setViewName("approve_baoxiao");
        return mv;
    }

    /**
     * 推进流程
     * @param id
     * @param taskId
     * @param comment
     * @param session
     * @return
     */
    @RequestMapping("/submitTask")
    public String submitTask(long id , String taskId,BaoXiaoBill baoxiao,String outcome,String comment,HttpSession session){
        ActiveUser employee = (ActiveUser) session.getAttribute(Contants.GLOBAL_SESSION_ID);
        System.out.println("money="+baoxiao.getMoney());
        ReimbFlowService.saveSubmitTask(id,taskId,baoxiao.getMoney(),outcome,comment,employee.getUsername());
        return "redirect:/myTaskList";
    }

    /**
     * 查看流程定义图
     * @throws Exception
     */
    @RequestMapping("/viewImage")
    //@RequiresPermissions("baoxiao:viewimage")
    public String viewImage(String deploymentId, String imageName, HttpServletResponse response) throws Exception{

        //2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        InputStream in = ReimbFlowService.findImageInputStream(deploymentId,imageName);
        //3：从response对象获取输出流
        OutputStream out = response.getOutputStream();
        //4：将输入流中的数据读取出来，写到输出流中
        for(int b=-1;(b=in.read())!=-1;){
            out.write(b);
        }
        out.close();
        in.close();
        return null;
    }

    /**
     * 查看当前流程图（查看当前活动节点，并使用红色的框标注）
     */
    @RequestMapping("/viewCurrentImage")
    public String viewCurrentImage(String taskId, ModelMap model){
        //billId-->taskId
        /**一：查看流程图*/
        //1：获取任务ID，获取任务对象，使用任务对象获取流程定义ID，查询流程定义对象
        System.out.println("taskId = " + taskId);
        ProcessDefinition pd = ReimbFlowService.findProcessDefinitionByTaskId(taskId);
        model.addAttribute("deploymentId", pd.getDeploymentId());
        model.addAttribute("imageName", pd.getDiagramResourceName());
        /**二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中*/
        Map<String, Object> map = ReimbFlowService.findCoordingByTask(taskId);

        model.addAttribute("acs", map);
        return "viewimage";
    }

    /**
     * 插卡可能我的报销单页面
     * @param session
     * @param model
     * @param pageNum
     * @return
     */
    @RequestMapping("/myBaoxiaoBill")
    public String toBaoXiaoBill(HttpSession session, Model model,Integer pageNum){
        ActiveUser user= (ActiveUser) session.getAttribute(Contants.GLOBAL_SESSION_ID);
        Employee employee=new Employee();
        employee.setId(user.getId());
        employee.setName(user.getUsername());
//        System.out.println(pageNum);
        if (pageNum==null){
            pageNum=1;
        }
        List<BaoXiaoBill> baoxiaos=ReimbFlowService.findMyBaoXiaoBillByUser(employee,false,1);
        List<BaoXiaoBill> list=ReimbFlowService.findMyBaoXiaoBillByUser(employee,true,pageNum);
        model.addAttribute("baoxiaoList",list);
        model.addAttribute("baoxiaos", baoxiaos.size());
        model.addAttribute("page", pageNum);
        return "baoxiaobill";
    }


    /**
     * 删除我的报销单
     * @param id
     * @return
     */
    @RequestMapping("/deleteBill")
    public String deleteBill(String id){
        System.out.println(id);
        ReimbFlowService.deleteBillById(id);
        return "redirect:/myBaoxiaoBill";
    }


    /**
     * 查看当前流程执行位置图
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/viewCurrentImageByBill")
    public String viewCurrentImageByBill(long id,ModelMap model){
        System.out.println(id);
        String BUSSINESS_KEY=Contants.BAOXIAO_KEY+"."+id;
        Task task=this.ReimbFlowService.findTaskByBussinessKey(BUSSINESS_KEY);
        ProcessDefinition pd = ReimbFlowService.findProcessDefinitionByTaskId(task.getId());
        model.addAttribute("deploymentId", pd.getDeploymentId());
        model.addAttribute("imageName", pd.getDiagramResourceName());
        Map<String,Object> map=ReimbFlowService.findCoordingByTask(task.getId());
        model.addAttribute("acs", map);
        return "viewimage";
    }

    /**
     * 查看审批记录
     * @param id
     * @return
     */
    @RequestMapping("/findCommentByBaoxiaoBillId")
    public ModelAndView findCommentByBaoxiaoBillId(long id){
        List<Comment> comments = ReimbFlowService.findCommentByBaoxiaoBillId(id);
        BaoXiaoBill bill=ReimbFlowService.findBillById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("bill", bill);
        mv.addObject("commentList", comments);
        mv.setViewName("approve_leave");
        return mv;
    }

    /**
     * 删除已经部署的流程
     * @param deploymentId
     * @return
     */
    @RequestMapping("/delDeployment")
    public String delDeployment(String deploymentId){
        System.out.println("deploymentId = " + deploymentId);
        ReimbFlowService.delDeploymentById(deploymentId);
        return "redirect:/processDefinitionList";
    }


    /**
     * 查看用户列表
     * @return
     */
    @RequestMapping("/findUserList")
    public ModelAndView toUserList(){
        List<EmployeeCustom> list=sysPermissionCustomMapper.findUserAndRoleList();
        List<SysRole> allRole =sysService.findAllRole();
        List<SysUserRole> urs=sysService.getUserAndRoleList();
        ModelAndView mv = new ModelAndView();
        mv.addObject("userRoles",urs);
        mv.addObject("userList",list);
        mv.addObject("allRoles", allRole);
        mv.setViewName("userlist");
        return mv;
    }

    /**
     * 修改权限
     * @param roleId
     * @param username+
     * @return
     */
    @RequestMapping("/assignRole")
    @ResponseBody
    public Map<String,String> assignRole(String roleId,String username){
        System.out.println(roleId);
        HashMap<String, String> map = new HashMap<>();

        try {
            employeeService.updateEmployeeRole(roleId,username);
            map.put("msg", "分配权限成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "分配权限失败");
        }
        return map;
    }

    /**
     * 查看该用户的角色和权限
     * @param userName
     * @return
     */
    @RequestMapping("/viewPermissionByUser")
    @ResponseBody
    public SysRole viewPermissionByUser( String userName){
        System.out.println("userName="+userName);
        SysRole role = sysPermissionCustomMapper.findRoleAndPermissionListByUserId(userName);
        return role;
    }

    /**
     * 通过username修改权限
     * @param roleId
     * @param username
     * @return
     */
    @RequestMapping("/updatePermissionByUser")
    @ResponseBody
    public Map<String,String> updatePermissionByUser(String roleId,String username){
//        System.out.println("roleId="+roleId+",username="+username);
        HashMap<String, String> map = new HashMap<>();
        employeeService.updateEmployeeRole(roleId, username);
        map.put("msg","修改成功!");
        return map;
    }

    /**
     * 新建一个用户
     * @param employee
     * @return
     */
    @RequestMapping("/saveUser")
    public String saveUser(Employee employee){
        String salt="eteokues";
        Md5Hash psw = new Md5Hash(employee.getPassword() , salt);
        employee.setPassword(psw.toString());
        employee.setSalt(salt);
        employeeService.addUser(employee);
        System.out.println("employee.getId() = " + employee.getId());
        sysService.addUser(employee);
        return "redirect:/findUserList";
    }

    /**
     * 跳转到角色列表页面
     * @return
     */
    @RequestMapping("/toAddRole")
    public ModelAndView toAddRole(){
        List<TreeMenu> treeMenus = sysService.loadTreeMenu();
        ModelAndView mv = new ModelAndView();
        mv.addObject("allPermissions", treeMenus);
        mv.setViewName("rolelist");
        return mv;
    }

    /**
     * 查看所有的角色
     * @return
     */
    @RequestMapping("/findRoles")
    public ModelAndView findRoles(){
        ModelAndView mv = new ModelAndView();
        List<SysRole> allRole = sysService.findAllRole();
        List<TreeMenu> treeMenus = sysService.loadTreeMenu();
        mv.addObject("allRoles", allRole);
        mv.addObject("allMenuAndPermissions", treeMenus);
        mv.setViewName("permissionlist");
        return mv;

    }

    /**
     * 加载所有的权限信息
     * @param roleId
     * @return
     */
    @RequestMapping("/loadMyPermissions")
    @ResponseBody
    public List<SysPermission> loadMyPermissions(String roleId){
        List<SysPermission> list=sysPermissionCustomMapper.findPermssionByRoleId(roleId);
        return list;
    }

    /**
     * 禁止该角色的使用
     * @param roleId
     * @return
     */
    @RequestMapping("/delRoleById")
    @ResponseBody
    public Map<String,String> delRoleById(String roleId){
        HashMap<String, String> map = new HashMap<>();
        System.out.println("删除角色的id"+roleId);
        try {
            sysService.delRoleById(roleId);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "禁用失败");
        }
        map.put("msg", "禁用成功");
        return map;
    }

    /**
     * 恢复角色的使用
     * @param roleId
     * @return
     */
    @RequestMapping("/reRoleById")
    @ResponseBody
    public Map<String,String> reRoleById(String roleId){
        HashMap<String, String> map = new HashMap<>();
        System.out.println("启用角色的id"+roleId);
        try {
            sysService.reRoleById(roleId);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "启用失败");
        }
        map.put("msg", "启用成功");
        return map;
    }

    /**
     * 修改角色所拥有的权限
     * @param roleId
     * @param permissionIds
     * @return
     */
    @RequestMapping("/updateRoleAndPermission")
    public String updateRoleAndPermission(String roleId,String[] permissionIds){
//        System.out.println("wwww"+roleId);
//        System.out.println(Arrays.toString(permissionIds));
        sysService.updateRoleAndPermission(roleId,permissionIds);
        return "redirect:/findRoles";
    }

    /**
     * 新建权限
     * @param permission
     * @return
     */
    @RequestMapping("/saveSubmitPermission")
    public String saveSubmitPermission(SysPermission permission){
        System.out.println(permission);
        sysService.addRole(permission);
        return "redirect:/toAddRole";
    }

    /**
     * 新建角色和他的权限
     * @param name
     * @param permissionIds
     * @return
     */
    @RequestMapping("/saveRoleAndPermissions")
    public String saveRoleAndPermissions(String name,String[] permissionIds){
//        System.out.println(name +",aaaa,"+Arrays.toString(permissionIds));
        sysService.addRoleAndPermission(name ,permissionIds);
        return "redirect:/findRoles";
    }
}
